package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     *
     * @param dto
     * @return
     */
    @Override
    public Result<OrderSubmitVO> submit(OrdersSubmitDTO dto) {
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        ShoppingCart shoppingCart=new ShoppingCart();
        ShoppingCart queryShoppingCar = shoppingCartMapper.queryShoppingCar(shoppingCart);
        //如果地址为空
        if (addressBook==null){
            return Result.error(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }//如果购物车为空
        if (queryShoppingCar==null){
            return Result.error(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //插入订单表
        Orders orders=new Orders();
        BeanUtils.copyProperties(dto,orders);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setUserId(addressBook.getUserId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(orders.UN_PAID);
        orders.setStatus(orders.PENDING_PAYMENT);
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());//
        orders.setConsignee(addressBook.getConsignee());
        orderMapper.insert(orders);
        //插入订单明细表
/*        List<OrderDetail>orderDetailList=new ArrayList<>();
        OrderDetail orderDetail=new OrderDetail();
        orderDetail.setOrderId(orders.getId());
        BeanUtils.copyProperties(orderDetail,orderDetailList);
        orderDetailList.add(orderDetail);*/
        //
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(userId);
        List<OrderDetail> orderDetailList=new ArrayList<>();
        for (ShoppingCart shopping : shoppingCartList) {
            OrderDetail orderDetail=new OrderDetail();
            BeanUtils.copyProperties(shopping,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        //调用mapper
        orderDetailMapper.insertOrderDetail(orderDetailList);
        //封装数据
        OrderSubmitVO vo=OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();

        return Result.success(vo);
    }

    /**
     * 历史订单查询
     *
     * @param page
     * @param pageSize
     * @param status   订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
     * @return
     */
    @Override
    public Result<PageResult> page(int page, int pageSize, Integer status) {
        //设置分页
        PageHelper.startPage(page,pageSize);
        OrdersPageQueryDTO dto=new OrdersPageQueryDTO();
        dto.setUserId(dto.getUserId());
        dto.setStatus(status);
        // 分页条件查询
        Page<Orders> ordersPageage = orderMapper.page(dto);
        // 查询出订单明细，并封装入OrderVO进行响应
        List<OrderVO> voList=new ArrayList<>();
        if (ordersPageage != null && ordersPageage.getTotal() > 0) {
            for (Orders orders : ordersPageage) {
                // 查询订单明细
                Long ordersId = orders.getId();
                List<OrderDetail> byOrderId = orderDetailMapper.getByOrderId(ordersId);
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                //set订单详情
                orderVO.setOrderDetailList(byOrderId);
                voList.add(orderVO);
            }
        }
        PageResult pageResult=new PageResult(ordersPageage.getTotal(),voList);
        return Result.success(pageResult);
    }

    /**
     * 根据id查询订单详细信息
     *
     * @param id
     * @return
     */
    @Override
    public Result<OrderVO> getById(Long id) {
        // 根据id查询订单
        Orders Orders = orderMapper.getById(id);
        // 查询该订单对应的菜品/套餐明细
        List<OrderDetail> byOrderId = orderDetailMapper.getByOrderId(Orders.getId());
        // 将该订单及其详情封装到OrderVO并返回
        OrderVO orderVO=new OrderVO();
        BeanUtils.copyProperties(Orders,orderVO);
        orderVO.setOrderDetailList(byOrderId);
        return Result.success(orderVO);
    }

    /**
     *user 催单
     *
     * @param id
     * @return
     */
    @Override
    public Result reminderId(Long id) {
        //查询订单是否存在
        Orders orders = orderMapper.getById(id);
        if (orders==null){
            return Result.error(MessageConstant.ORDER_NOT_FOUND);
        }
        //封装数据
        Map Map=new HashMap();
        Map.put("id",id);
        Map.put("type", 2);//2代表用户催单
        Map.put("number","订单号："+orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(Map));
        return Result.success(Map);
    }

    /**
     * admin订单查询
     *
     * @param dto
     * @return
     */
    @Override
    public Result<PageResult> conditionSearch(OrdersPageQueryDTO dto) {
        //开启分页
        PageHelper.startPage(dto.getPage(), dto.getPageSize());

        Page<Orders> page = orderMapper.page(dto);

        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(page);
        PageResult pageResult = new PageResult(page.getTotal(), orderVOList);
        return Result.success(pageResult);
    }

    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }
    /**
     * admin各个状态的订单数量统计
     *
     * @return
     */
    public OrderStatisticsVO statistics() {
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        // 将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }
}
